package com.sepro.action.admin;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.xwork.StringUtils;
import com.sepro.action.BaseAction;
import com.sepro.entity.Admin;
import com.sepro.entity.Member;
import com.sepro.exception.MemberNotExistException;
import com.sepro.exception.PasswordMatchFailedException;
import com.sepro.service.AdminService;

public class AdminAction extends BaseAction {

	private static final long serialVersionUID = 4304045166604034979L;

	private String username; //注册用户名
	private String password; //登录或注册密码
	private String errorMessage; //错误信息

	/**
	 * @return the errorMessage
	 */
	public String getErrorMessage() {
		return errorMessage;
	}
	
	/**
	 * @param errorMessage the errorMessage to set
	 */
	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}
	
	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}
	
	/**
	 * @param username the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}
	
	@Resource(name="adminServiceImpl")
	private AdminService adminService;
	
	/**
	 * Submit login action
	 * handle the user login request
	 * 
	 * @return "result", "error"
	 */
	public String login(){
		
		if(StringUtils.isEmpty(username)){
			errorMessage = "用户名不能为空!";
			return ERROR;
		}
		if(StringUtils.isEmpty(password)){
			//return ajax(Status.error, "登录密码不能为空!");
			errorMessage = "登录密码不能为空!";
			return ERROR;
		}
		
		Admin admin = null;
		try{
			admin = adminService.verifyAdmin(username, password);
			String adminId = admin.getId();
			if(!StringUtils.isEmpty(adminId)){
				
				admin.setLoginIp(getRequest().getRemoteAddr());
				admin.setLoginDate(new Date());
				adminService.update(admin);
				
				// 防止Session Fixation攻击
				HttpSession httpSession = getRequest().getSession();
				Enumeration enumeration = httpSession.getAttributeNames();
				Map<String, Object> sessionMap = new HashMap<String, Object>();
				while (enumeration.hasMoreElements()) {
					String key = (String) enumeration.nextElement();
					sessionMap.put(key, httpSession.getAttribute(key));
				}
				httpSession.invalidate();
				httpSession = getRequest().getSession(true);
				for (String key : sessionMap.keySet()) {
					Object value = sessionMap.get(key);
					httpSession.setAttribute(key, value);
				}
				
				// 写入管理员 Session Name
				httpSession.setAttribute(Admin.ADMIN_ID_SESSION_NAME, adminId);
				
				// 写客户端 Cookie
				try {
					setCookie(Admin.ADMIN_NAME_COOKIE_NAME, URLEncoder.encode(admin.getUsername(), "UTF-8"));
					setCookie(Admin.ADMIN_ID_COOKIE_NAME, admin.getId());
				} catch (UnsupportedEncodingException e) {
					//TODO
				}
				
				return SUCCESS;
			}else{
				errorMessage = "管理员的ID异常：为空!";
				return ERROR;
			}
		} catch(PasswordMatchFailedException e){
			//return ajax(Status.error, "密码与用户名不匹配!");
			errorMessage = "管理员密码错!";
			return ERROR;
		} catch (MemberNotExistException e) {
			//return ajax(Status.error, "用户不存在，请先注册!");
			errorMessage = "该管理员的用户名不存在!";
			return ERROR;
		}
	}
	
	public String main(){
		return SUCCESS;
	}
	
	// 会员注销
	public String logout() {
		removeSession(Admin.ADMIN_ID_SESSION_NAME);
		removeCookie(Admin.ADMIN_ID_COOKIE_NAME);
		removeCookie(Admin.ADMIN_NAME_COOKIE_NAME);
		return "index";
	}
	
}
